<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="100px" :rules="rules">
                <el-row>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="公告日期" prop="d_PublicDate">
                            <el-date-picker
                                v-model="ruleForm.d_PublicDate"
                                type="datetime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                placeholder="请选择日期"
                                popper-class="el-date-p"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="主要负责人" prop="v_Principal">
                            <el-input v-model="ruleForm.v_Principal" placeholder="主要负责人" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="描述" prop="v_Content">
                            <el-input type="textarea" autosize v-model="ruleForm.v_Content" placeholder="描述" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="公告内容" prop="v_FileBase64">
                            <el-input class="set-inp" type="textarea" v-model="ruleForm.v_FileBase64" placeholder="公告内容" clearable />
                            <!-- <Toolbar
                                style="border-bottom: 1px solid #ccc;width: 100%;"
                                :editor="editorRef"
                                :defaultConfig="toolbarConfig"
                                :mode="mode"
                                class="tool-bar"
                            />
                            <Editor
                                style="height: 500px; overflow-y: auto;width: 100%;"
                                v-model="valueHtml"
                                :defaultConfig="editorConfig"
                                :mode="mode"
                                @onCreated="handleCreated"
                            /> -->
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { 
    defineComponent, 
    ref, 
    reactive , 
    computed , 
    toRef , 
    toRefs , 
    toRaw , 
    onMounted , 
    onBeforeUnmount,
    shallowRef,
    watch ,
} from 'vue';

import { 
    FormInstance, 
    FormRules , 
    ElMessage, 
    ElButton, 
    ElCol, 
    ElDatePicker, 
    ElDialog, 
    ElForm, 
    ElFormItem, 
    ElInput,
    ElRow, 
} from 'element-plus';
import { SMSDCRiskJudPubAdd , SMSDCRiskJudPubUpdate } from '/@/api/centerControl/sms';
import { sysFileInfoYitId } from '/@/api/centerControl/pubilc';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { IToolbarConfig , DomEditor } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { asBlob } from 'html-docx-js-typescript';
import { saveAs } from 'file-saver';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    d_PublicDate: String, // 公告日期
    v_Principal: String, // 主要负责人
    v_Content: String, // 描述
    l_FileId: Number, // 内容文档id
    v_FileBase64: String, // rtf格式公告内容文档Base64
    v_FileCotent: String, // 用于数据回显
}
export default defineComponent( {
    name: 'add-edit-CommitmentCard',
    components: {Editor, Toolbar},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        
        const editorRef = shallowRef();
        const valueHtml = ref();
        const toolbarConfig: Partial<IToolbarConfig> = {};
        const editorConfig = { placeholder: '请输入内容...' };
        // 排除掉不需要的菜单
        toolbarConfig.excludeKeys = [
            'blockquote',
            'underline',
            'emotion',
            'insertLink',
            'group-image',
            'group-video',
            'insertTable',
            'codeBlock',
            'divider',
            'group-more-style',
        ];


        // 组件销毁时，也及时销毁编辑器
        onBeforeUnmount(() => {
            const editor = editorRef.value;
            if (editor == null) return;
            editor.destroy();
        })

        const handleCreated = (editor: any) => {
            editorRef.value = editor // 记录 editor 实例，重要！
        }

        /*** 创建html文件 */
        const creatHtmlFile = (con: any) => {
            return `<!DOCTYPE html>
                <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <title>Document</title>
                    </head>
                    <body>
                        ${con}
                    </body>
            </html>`;
        }

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 公告日期
            d_PublicDate: [
				{ required: true, message: '请选择公告日期', trigger: 'change' },
			],
            // 主要负责人
            v_Principal: [
				{ required: true, message: '请输入主要负责人', trigger: 'blur' },
			],
            // 描述
            v_Content: [
				{ required: true, message: '请输入描述', trigger: 'blur' },
			],
            // rtf格式公告内容文档Base64
            v_FileBase64: [
				{ required: true, message: '请输入公告内容', trigger: 'blur' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick');
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => {
                if(valid){
                    try{
                        let res: any;
                        let param: any = state.ruleForm;
                        param.v_FileCotent = state.ruleForm.v_FileBase64;
                        console.log(param,'param')
                        // param.v_FileBase64 = event.target.result.split('base64,')[1];
                        // param.v_FileCotent = valueHtml.value;
                        state.repeatDis = true;
                        if(props.repairInfo === ''){
                            res =  await SMSDCRiskJudPubAdd(param);
                        }else{
                            res = await SMSDCRiskJudPubUpdate(param);
                        }   
                        if(res.success){
                            state.repeatDis = false;
                            ctx.emit('updateData');
                            ctx.emit('controlUseClick');
                        }else{
                            state.repeatDis = false;
                            ctx.emit('controlUseClick');
                        }
                    }catch(error){ state.repeatDis = false; }
                    return
                    const htmlStr = valueHtml.value; 
                    if(!htmlStr){
                        ElMessage({
                            type: 'error',
                            message: '公告内容不能为空',
                        });
                        return;
                    }
                    const wrappedHtml = `<div>${htmlStr}</div>`;
                    const htmlVal = creatHtmlFile(wrappedHtml);
                    // 转world文档
                    asBlob(htmlVal).then((data: any) => {
                        // 将生成的world文档转换成base64
                        const reader = new FileReader();
                        reader.onload = async (event: any) => {
                            state.ruleForm.v_FileBase64 = event.target.result.split('base64,')[1];
                            try{
                                let res: any;
                                let param: any = state.ruleForm;
                                param.v_FileBase64 = event.target.result.split('base64,')[1];
                                param.v_FileCotent = valueHtml.value;
                                console.log(param,'param')
                                state.repeatDis = true;
                                if(props.repairInfo === ''){
                                    res =  await SMSDCRiskJudPubAdd(param);
                                }else{
                                    res = await SMSDCRiskJudPubUpdate(param);
                                }   
                                if(res.success){
                                    state.repeatDis = false;
                                    ctx.emit('updateData');
                                    ctx.emit('controlUseClick');
                                }else{
                                    state.repeatDis = false;
                                    ctx.emit('controlUseClick');
                                }
                            }catch(error){ state.repeatDis = false; }
                        };
                        reader.readAsDataURL(data);
                        // saveAs(data, 'file.docx'); // 自动下载生成的html文件
                    });
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /** 获取雪花id */
        const getXhFun = async() => {
            let res: any = await sysFileInfoYitId({});
            if(res.success) state.ruleForm.l_FileId = res.data;
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                state.repeatDis = false;
                valueHtml.value = '';
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑';
                    let getData = JSON.parse(props.repairInfo);
                    state.ruleForm = getData;
                    return
                    let setTime = setInterval(() => {
                        valueHtml.value = getData.v_FileCotent;
                        clearInterval(setTime);
                    }, 20);
                }else{
                    titleCon.value = '新增';
                    getXhFun();
                    state.ruleForm = {
                        d_PublicDate: '', // 公告日期
                        v_Principal: '', // 主要负责人
                        v_Content: '', // 描述
                        l_FileId: 0, // 内容文档id
                        v_FileBase64: '', // rtf格式公告内容文档Base64
                        v_FileCotent: '', // 用于数据回显
                    }
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,

            editorRef,
            valueHtml,
            mode: 'default', //'default' 或 'simple'
            toolbarConfig,
            editorConfig,
            handleCreated,
        }
    },
} )
</script>
<style lang="scss">
[data-theme='dark'] {
    .tool-bar{
        background-color: var(--el-dialog-bg-color);
        border: 1px solid #fff;
        .w-e-bar{
            background-color: transparent!important;
        }
        .w-e-menu-tooltip-v5:before{
            content: '';
            background-color: transparent;
        }
        .w-e-bar{
            color: #636466;
        }
        .w-e-bar-item-menus-container{
            .w-e-bar-item{
                button{
                    color: #636466;
                    svg{
                        fill: #636466;
                    }
                }
            }
        }
        .w-e-bar-item .disabled:hover{
            background-color: var(--w-e-toolbar-active-bg-color);
        }
    }
}
</style>
<style scoped lang="scss">
:deep(.w-e-text-container){
    font-family: Arial, sans-serif;
    font-size: 14px;
    color: #363637;
    min-height: 300px !important;
    overflow-y: auto;
}
:deep(.w-e-hover-bar) {
    display: none!important;
}
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
:deep(.w-e-item){
    // display: show !important;
}
.set-inp{
    :deep(.el-textarea__inner){
        min-height: 500px !important;
    }
}
</style>